package com.example.order.RocketMq;

import com.example.common.Interface.order.entity.vo.OrderVO;
import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.client.producer.SendResult;
import org.apache.rocketmq.spring.core.RocketMQTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.messaging.support.MessageBuilder;
import org.springframework.stereotype.Component;

@Component
@Slf4j
public class MQOrderProducer {
    private static final String topic = "ORDER_TOPIC";
    private static final String cancelOrder_tag = ":CANCEL_ORDER_TAG";
    private static final String deductStock_tag = ":DEDUCT_STOCK_TAG";
    private static final String addStock_tag = ":ADD_STOCK_TAG";

    @Value("${rocketmq.producer.send-message-timeout}")
    private Integer messageTimeOut;
    @Autowired
    private RocketMQTemplate rocketMQTemplate;

    /**
     * 发送延时消息（上面的发送同步消息，delayLevel的值就为0，因为不延时）
     * 在start版本中 延时消息一共分为18个等级分别为：1s 5s 10s 30s 1m 2m 3m 4m 5m 6m 7m 8m 9m 10m 20m 30m 1h 2h
     */
    public void sendDelayMsg(String msgBody, int delayLevel) {
        rocketMQTemplate.syncSend(topic, MessageBuilder.withPayload(msgBody).build(),messageTimeOut, delayLevel);
    }

    public void sendDelayMsg(OrderVO order, int delayLevel) {
        rocketMQTemplate.syncSend(topic, MessageBuilder.withPayload(order).build(),messageTimeOut, delayLevel);
    }
    /**
     * 发送单向消息（只负责发送消息，不等待应答，不关心发送结果，如日志）
     */
    public void sendOneWayMsg(String msgBody) {
        rocketMQTemplate.sendOneWay(topic, MessageBuilder.withPayload(msgBody).build());
    }

    /**
     * 发送带tag的消息，直接在topic后面加上":tag"
     */
    public SendResult sendTagMsgCancelOrder(String msgBody) {
        return rocketMQTemplate.syncSend(topic, MessageBuilder.withPayload(msgBody)
                .setHeader("TAGS", cancelOrder_tag).build());
    }

    public SendResult sendTagMsgDeductStock(String msgBody) {
        return rocketMQTemplate.syncSend(topic, MessageBuilder.withPayload(msgBody)
                .setHeader("TAGS", deductStock_tag).build());
    }

    public SendResult sendTagMsgAddStock(String msgBody) {
        return rocketMQTemplate.syncSend(topic, MessageBuilder.withPayload(msgBody)
                .setHeader("TAGS", addStock_tag).build());
    }
}
